package com.ruoyi.framework.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author 最爱喝兽奶
 * @create 2022/6/12
 **/
@Configuration
public class OssConfig {

    private final Logger logger = LoggerFactory.getLogger(OssConfig.class);

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.accessKey}")
    private String accessKey;

    @Value("${oss.secretKey}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = null;
        try {
            minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        // 创建桶

        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                // 如果当前需要创建的bucket不存在就创建一个桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                // TODO：暂未设定策略
            }
            return minioClient;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建bucket失败，请检查配置", e);
        }

        return null;
    }

}
